package com.example.mqttxconsumer.callback;

import com.example.mqttxconsumer.config.MqttxProviderConfig;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 实现MqttCallback   用来对回调事件进行处理
 */
@Component
public class MqttProviderCallBack implements MqttCallback {

    @Resource
    private MqttxProviderConfig client;
    /**
     * 客户端断开连接 回调
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("客户端与服务器断开连接，可重新尝试连接");
        System.out.println("自动尝试建立连接");
        client.connect();
    }

    /**
     * 消息到达回调
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        System.out.println(String.format("接收消息主题 : %s",topic));
        System.out.println(String.format("接收消息Qos : %d",mqttMessage.getQos()));
        System.out.println(String.format("接收消息内容 : %s",new String(mqttMessage.getPayload())));
        System.out.println(String.format("接收消息retained : %b",mqttMessage.isRetained()));
    }

    /**
     * 消息发布回调
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        System.out.println(String.format("接收消息成功"));
    }
}
